namespace BM.Tools.WebControls.MForm.Navigation
{
    using System.Collections.Generic;
    using System.Linq;

    using BM.Tools.WebControls.MForm.Navigation.XPath;

    /// <summary>
    /// A navigator for the <see cref="CompoundLocationStep" /> locator.
    /// </summary>
    /// <typeparam name="T">
    /// The type of the navigable object.
    /// </typeparam>
    public class CompoundLocationStepNavigator<T> : LocationStepNavigator<T, CompoundLocationStep>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CompoundLocationStepNavigator{T}"/> class. 
        /// </summary>
        /// <param name="parent">
        /// The parent.
        /// </param>
        /// <param name="locationStep">
        /// The location step.
        /// </param>
        public CompoundLocationStepNavigator(INavigator<T> parent, CompoundLocationStep locationStep)
                : base(parent, locationStep)
        {
        }

        /// <summary>
        /// Returns a distinct enumerable of items from all location steps that are within this compund location step
        /// </summary>
        /// <returns>
        /// the enumerable of items
        /// </returns>
        public override IEnumerable<T> Select()
        {
            return SelectAll().Distinct();
        }

        private IEnumerable<T> SelectAll()
        {
            foreach (LocationStep locationStep in Locator.CompoundElements)
            {
                var locationStepNavigator = Create(Parent, locationStep);
                foreach (T child in locationStepNavigator.Select())
                {
                    yield return child;
                }
            }
        }
    }
}